<template>
  <el-row style="margin-top: 15px">
    <el-col :span="12">
      <el-image src="/api/file/images/1838872607454674944.jpg" />
    </el-col>
    <el-col :span="12">
      <el-form label-width="auto" class="loginInfo">
        <h1>用户登录</h1>
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="userInfo.username"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" placeholder="请输入密码" v-model="userInfo.password"/>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input  style="width: 120px; margin-right: 5px" placeholder="请输入验证码" v-model="userInfo.captchaInput"/>
          <el-image :src="imgBase64" @click="getCaptcha" style="height: 32px"></el-image>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="loginBtn" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup>
import userApi from "@/api/UserApi.js";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {tokenStore} from "@/stores/token.js";
import {userStore} from "@/stores/user.js";

// 保存验证码
const imgBase64 = ref(null)
// 用户注册信息
const userInfo = ref({
  username:'',
  password:'',
  key:'',
  captchaInput:''
})

// token
const token = tokenStore()
// user
const user = userStore()

// 获取登录验证码
const getCaptcha = () => {
  userApi.captcha()
      .then(resp => {
        if (resp.code === 10000) {
          userInfo.value.key = resp.data.key
          imgBase64.value ='data:image/png;base64,' +  resp.data.imageBase64Data;
        }
      })
}

// 用户登录
const login = () => {
  userApi.login(userInfo.value.username, userInfo.value.password, userInfo.value.key, userInfo.value.captchaInput)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          // 保存token
          token.updateToken(resp.data)
          // 获取用户信息
          getInfo()
          // 页面跳转 前往前台首页
          router.push('/user/index')
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 获取用户信息
const getInfo = () => {
  userApi.getInfo()
      .then(resp => {
        if (resp.code === 10000) {
          //   将已登录用户信息保存在pina中
          user.updateUser(resp.data)
        }
      })
}
getCaptcha()
</script>

<style scoped>
.loginInfo {
  width: 300px;
  margin: 45px 100px;
}

.loginInfo h1 {
  text-align: center;
  margin-bottom: 20px;
}

.loginBtn {
  width: 100%;
}
</style>